package com.power.flowable.dao.impl;

import com.plf.core.common.dao.OffersetTransformers;
import com.power.flowable.dao.SfapproveFlowableDao;
import org.hibernate.query.internal.NativeQueryImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Repository
public class SfapproveFlowableDaoImpl implements SfapproveFlowableDao {

    @Autowired
    private EntityManager entityManager;

    @Override
    public List<Map<String, Object>> queryCandidateusers(List<String> groupids, List<String> userids) {

        StringBuffer sql = new StringBuffer("select * from ( select row_number() over(partition by a.userid order by a.userid desc) as kfid, a.userid, a.fullname, c.departid  from ha_user a left join ha_role_user b on a.userid = b.userid  left join ha_depart_user c on a.userid = c.userid where 1=1 ");
        List params = new ArrayList();
        if (!CollectionUtils.isEmpty(groupids)) {
            sql.append(" and b.roleid in ( ");
            for (int i = 0; i < groupids.size(); i++) {
                params.add(groupids.get(i));
                if (i != groupids.size() - 1) {
                    sql.append(" ?,");
                } else {
                    sql.append(" ?)");
                }
            }
        }
        if (!CollectionUtils.isEmpty(userids)) {
            sql.append(" or a.userid in ( ");
            for (int i = 0; i < userids.size(); i++) {
                params.add(userids.get(i));
                if (i != userids.size() - 1) {
                    sql.append(" ?,");
                } else {
                    sql.append(" ?)");
                }
            }
        }
        sql.append(") where kfid = 1");
        Query query = entityManager.createNativeQuery(sql.toString());
        query.unwrap(NativeQueryImpl.class).setResultTransformer(OffersetTransformers.ALIAS_TO_ENTITY_MAP);

        // 添加条件
        for (int i = 0; i <= params.size() - 1; i++) {
            query.setParameter(i + 1, params.get(i));
        }
        return query.getResultList();
    }

}
